    public static int threeSumClosest(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Arrays.sort(num);   
        int res = 0, diff = Integer.MAX_VALUE;
        if (num.length < 3) return 0;
        for (int i = 0; i < num.length-2; i++) {
	    int need = target - num[i];
	    int j = i+1, k = num.length -1;
	    while (j < k) {
		int sum = num[j] + num[k] + num[i];
		if (sum == target) return target;
		else if (num[j] + num[k] > need) {
		    if (sum- target < diff) {
			diff = sum - target;
			res = sum;
		    }
		    k--;
		} else {
		    if (target - sum < diff) {
			diff = target - sum;
			res = sum;
		    }   
		    j++;
		}
	    }
        }
        
        return res;
    }   
